<template>
  <div class="">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>实名认证</span>
        </div>
      </template>
      <!-- 提示 -->
      <div class="tip">
        <svg
          t="1696483704757"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="2548"
          width="16"
          height="16"
        >
          <path
            d="M512 32C246.912 32 32 246.912 32 512c0 265.088 214.912 480 480 480 265.088 0 480-214.912 480-480 0-265.088-214.912-480-480-480z m0 896C282.24 928 96 741.76 96 512S282.24 96 512 96s416 186.24 416 416-186.24 416-416 416z"
            p-id="2549"
            fill="#7f7f7f"
          ></path>
          <path
            d="M512 384a32 32 0 0 0-32 32v352a32 32 0 0 0 64 0V416a32 32 0 0 0-32-32z"
            p-id="2550"
            fill="#7f7f7f"
          ></path>
          <path
            d="M512 272m-48 0a48 48 0 1 0 96 0 48 48 0 1 0-96 0Z"
            p-id="2551"
            fill="#7f7f7f"
          ></path>
        </svg>
        完成实名认证后才能添加就诊人，正常进行挂号，为了不影响后续步骤，建议提前实名认证。
      </div>
      <!-- 未认证 -->
      <el-form
        ref="paramsRef"
        :rules="paramsRules"
        style="width: 500px"
        label-width="80px"
        v-if="userInfo.authStatus == 0"
        :model="params"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input placeholer="请输入姓名" v-model="params.name"></el-input>
        </el-form-item>
        <el-form-item label="证件类型" prop="certificatesType">
          <el-select
            placeholder="请选择证件类型"
            style="width: 100%"
            v-model="params.certificatesType"
          >
            <el-option
              v-for="item in ertificationType"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="certificatesNo">
          <el-input
            placeholer="请输入证件号码"
            v-model="params.certificatesNo"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传证件" prop="certificatesUrl">
          <!-- 
              action:图片上传的地址
              limit 限制上传张片个数
              on-exceed 超出数量钩子
           -->
          <el-upload
            ref="uploadRef"
            list-type="picture-card"
            action="/api/oss/file/fileUpload?fileHost=userAuah"
            :limit="1"
            :on-exceed="exceedhandler"
            :on-success="successhandler"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <img
              src="../../../assets//images/auth_example.png"
              alt=""
              style="width: 130px"
            />
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img
              w-full
              v-if="params.certificatesUrl"
              style="width: 100%; height: 100%"
              :src="params.certificatesUrl"
              alt="Preview Image"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit(paramsRef)">提交</el-button>
          <el-button @click="reset(paramsRef)">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 认证 -->
      <el-descriptions
        :column="1"
        border
        style="width: 600px; margin: 0 auto"
        v-if="userInfo.authStatus == 1"
      >
        <el-descriptions-item label-align="center">
          <template #label>
            <div class="cell-item">用户姓名</div>
          </template>
          {{ userInfo.name }}
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label>
            <div class="cell-item">证件类型</div>
          </template>
          {{ userInfo.certificatesType == "20" ? "身份证" : "户口本" }}
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label>
            <div class="cell-item">证件号码</div>
          </template>
          {{ userInfo.certificatesNo }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  reqUserInfo,
  reqCertificationType,
  userCertation,
} from "@/api/user/index";
import { UserParams } from "@/api/user/type";
import type { UploadProps } from "element-plus";
import type {
  UserInfo,
  UserInfoResponseData,
  CertationArr,
  CertationTypeResponseData,
} from "@/api/user/type";
import { ElMessage } from "element-plus";
// 已认证存储的数据
let userInfo = ref<UserInfo>({} as UserInfo);
// 身份证件类型
let ertificationType = ref<CertationArr>([] as CertationArr);
// 收集的数据
let params = reactive<UserParams>({
  certificatesNo: "",
  certificatesType: "",
  certificatesUrl: "",
  name: "",
});
// 自定义姓名规则
const validateName = (rule: any, value: any, callback: any) => {
  /* rule 当前规则 value 当前值 callback 回调 */
  console.log(value);
  let reg = /^([\u4e00-\u9fa5\·]{2,3})$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的中文姓名"));
  }
};
// 自定义身份证规则
const validateCertificatesNo = (rule: any, value: any, callback: any) => {
  let sfz =
    /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  let hkb = /^[a-zA-Z0-9]{3,9}$/;
  if (sfz.test(value) || hkb.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确的证件号码"));
  }
};
// 证件照自定义规则
const validateCertificatesUrl = (rule: any, value: any, callback: any) => {
  if (value.length) {
    callback();
  } else {
    callback(new Error("请输入正确的证件号"));
  }
};
// 表单验证规则
const paramsRules = reactive({
  name: [{ required: true, validator: validateName }],
  certificatesType: [
    {
      required: true,
      message: "请选择证件类型",
      trigger: "change",
    },
  ],
  certificatesNo: [
    {
      required: true,
      // max: 18,
      // message: "长度应为18位",
      validator: validateCertificatesNo,
      tirgger: "blur",
    },
  ],
  certificatesUrl: [{ required: true, validator: validateCertificatesUrl }],
});
// 图片预览框显示隐藏shuju
let dialogVisible = ref<boolean>(false);
const paramsRef = ref<any>();
const uploadRef = ref<any>();
onMounted(() => {
  fetchUserInfo();
  fetchCertificationType();
});
// 获取用户信息
const fetchUserInfo = async () => {
  /*
  certificatesType 10身份证 20户口本
  authStatus 0未验证 1验证
  */
  const reuslt: UserInfoResponseData = await reqUserInfo();
  if (reuslt.code == 200) {
    userInfo.value = reuslt.data;
  }
};
// 获取证件类型
const fetchCertificationType = async () => {
  const result: CertationTypeResponseData = await reqCertificationType();
  if (result.code == 200) {
    ertificationType.value = result.data;
  }
};
// 超出照片数量提示
const exceedhandler = () => {
  ElMessage({
    type: "error",
    message: "最多只能上传一张图片",
  });
};
// 图片上传成功钩子
const successhandler = (response: any, uploadFile: any, uploadFiles: any) => {
  // console.log(response, uploadFile, uploadFiles);
  /* response 上传图片请求服务器返回的数据
  uploadFuile上传文件的对象
  uploadFiles上传所有图片的集合 */
  // 收集图片路径
  params.certificatesUrl = response.data;
  // 图片上传成功以后清空证件照字段的校验文字
  paramsRef.value.clearValidate("certificatesUrl");
};
// 预览图片
const handlePictureCardPreview: UploadProps["onPreview"] = () => {
  dialogVisible.value = true;
};
// 删除图片
const handleRemove: UploadProps["onRemove"] = () => {
  params.certificatesUrl = "";
};
// 重置表单
// const reset = (formEl: any) => {
//   // Object.assign(params, {
//   //   certificatesNo: "",
//   //   certificatesType: "",
//   //   certificatesUrl: "",
//   //   name: "",
//   // });
//   formEl.resetFields();
// };
const reset = (formEl: any) => {
  // 清楚上传的图片
  uploadRef.value.clearFiles();
  // 清楚收集的数据
  if (!formEl) return;
  formEl.resetFields();
};
// 提交数据
const submit = async (formEl: any) => {
  if (!formEl) return;
  // 校验通过返回一个成功的promise true， 校验失败 false后面的语句不执行
  await formEl.validate();
  try {
    // 调接口
    await userCertation(params);
    // 提示信息
    ElMessage({
      type: "success",
      message: "认证成功",
    });
    // 重新获取数据
    fetchUserInfo();
  } catch (error) {
    ElMessage({
      type: "error",
      message: "认证失败",
    });
  }
};
</script>
<script lang="ts">
export default {
  name: "Certification",
};
</script>
<style scoped lang="scss">
::v-deep(.el-card__body) {
  .tip {
    color: #7f7f7f;
    margin-bottom: 20px;
    display: flex;
  }
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
